package com.hfzy.ihk.web.linkcall.controller.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.hfzy.ihk.common.util.FileUtils;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.http.HttpClientUtils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlowStep;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.type.IndustryType;
import com.hfzy.ihk.facade.linkcall.enums.AfterAnswerOptionalType;
import com.hfzy.ihk.facade.linkcall.enums.SpeakingFlowType;
import com.hfzy.ihk.facade.linkcall.enums.UploadRecordFileType;
import com.hfzy.ihk.facade.linkcall.vo.KnowledgeBaseResultVo;
import com.hfzy.ihk.facade.linkcall.vo.knowledgeBase.TreeNodeVo;
import com.hfzy.ihk.facade.linkcall.vo.service.RecordFilePackageVo;
import com.hfzy.ihk.facade.linkcall.vo.service.RecordFileVo;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.KnowledgeBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.QuestionBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.type.IndustryTypeBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowStepBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingPackageBiz;
import com.hfzy.ihk.web.linkcall.conf.PublicConfig;
import com.hfzy.ihk.web.linkcall.context.SpeechFunctionInitBean;
import com.hfzy.ihk.web.linkcall.controller.callTask.LinkageCallController;
import com.hfzy.ihk.web.linkcall.support.DefaultResult;
import com.hfzy.ihk.web.linkcall.support.tts.SpeechSynthesizerMultiThread;
import com.hfzy.ihk.web.linkcall.support.tts.SpeechTranscriberMultiThread;
import com.hfzy.ihk.web.linkcall.utils.UserUtils;
import com.hfzy.ihk.web.linkcall.utils.WebResultUtils;
import org.apache.catalina.util.ServerInfo;
import org.apache.tomcat.util.buf.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

/**
 * 录音文件接口类
 * 该接口供外部的访问 == 统一返回格式 ：application/json;charset=UTF-8
 * 指定con
 * ,produces = "application/json;charset=UTF-8"
 * */
@RestController
@RequestMapping(value = "api/recordFile")
public class RecordFileController {
    Logger logger = LoggerFactory.getLogger(RecordFileController.class);

    @Autowired
    SpeakingPackageBiz speakingPackageBiz;
    @Autowired
    SpeakingFlowStepBiz speakingFlowStepBiz;
    @Autowired
    SpeakingFlowBiz speakingFlowBiz;
    @Autowired
    private QuestionBaseBiz questionBaseBiz;

    @Autowired
    private KnowledgeBaseBiz knowledgeBaseBiz;

    @Autowired
    RedisTemplate redisTemplate;

    @Resource
    private SpeechFunctionInitBean speechFunctionInitBean;

    @Value("${spring.profiles.active}")
    public String profile;

    @Value("${aiService.knowledgebase.analysis.singleCall.url}")
    public String singleCallUrl;


    @Autowired
    IndustryTypeBiz industryTypeBiz;

    //分页查看话术包列表
    @ResponseBody
    @RequestMapping("/querySpeakingPackagePages")
    public DefaultResult querySpeakingPackagePages(String jsonStr){
        logger.info("querySpeakingPackagePages，jsonStr:"+jsonStr);
        Map params = JSON.parseObject(jsonStr,Map.class);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try{
            if(params!=null&&!params.isEmpty() && params.containsKey("page") && params.containsKey("pageSize")){
                Long timeStamp = System.currentTimeMillis();
                if(params.containsKey("timeStamp")){
                    timeStamp = Long.parseLong(params.get("timeStamp").toString());
                }
                Date createTime = Utils.long2Date(timeStamp);
                String createTimeEnd = Utils.date2DateTimeString(createTime);
                params.put("createTimeEnd",createTimeEnd);
                Page<SpeakingPackage> speakingPackages = speakingPackageBiz.getSpeakingPackageByPage(params);
                List<RecordFilePackageVo> recordFilePackageVos = new ArrayList();
                if(speakingPackages.getContent()!=null && !speakingPackages.getContent().isEmpty()){
                    for(SpeakingPackage speakingPackage:speakingPackages.getContent()){
                        RecordFilePackageVo recordFilePackageVo = new RecordFilePackageVo();
                        recordFilePackageVo.setPageckName(speakingPackage.getPackageName());
                        recordFilePackageVo.setId(speakingPackage.getId());
                        recordFilePackageVo.setModTime(speakingPackage.getModTime());
                        recordFilePackageVo.setModeTimeStr(Utils.date2DateString(speakingPackage.getModTime()));
                        //根据话术包获取完成量===>总的已经录音的话术
                        Map param = new HashMap();
                        param.put("packageId",speakingPackage.getId());
                        param.put("contentNoEmpty","");
                        //跟进话术包获取总量===>总的需要录入的话术
                        List<SpeakingFlowStep> speakingFlowStepList = speakingFlowStepBiz.getSpeakingFlowStepList(param);
                        int sum = 0;
                        int finishedCount = 0;
                        if(speakingFlowStepList!=null && !speakingFlowStepList.isEmpty()){
                            sum += speakingFlowStepList.size();
                            for(SpeakingFlowStep speakingFlowStep:speakingFlowStepList){
                                if(speakingFlowStep.getHadUploadFile() == true){
                                    finishedCount++;
                                }
                            }
                        }
                        List<KnowledgeBase> knowledgeBaseList = knowledgeBaseBiz.getKnowledgeBaseList(param);
                        if(knowledgeBaseList!=null && !knowledgeBaseList.isEmpty()){
                            sum += knowledgeBaseList.size();
                            for(KnowledgeBase knowledgeBase:knowledgeBaseList){
                                if(knowledgeBase.getHadUploadFile() == true){
                                    finishedCount++;
                                }
                            }
                        }
                        recordFilePackageVo.setFinishedNum(finishedCount);
                        recordFilePackageVo.setTotalNum(sum);
                        recordFilePackageVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                        String finishProgess = "0";
                        if(recordFilePackageVo.getFinishedNum()>0 && recordFilePackageVo.getTotalNum()>0){
                            DecimalFormat decimalFormat = new DecimalFormat("0");
                            finishProgess = decimalFormat.format(Utils.getRate(recordFilePackageVo.getFinishedNum(),recordFilePackageVo.getTotalNum())*100);
                        }
                        recordFilePackageVo.setFinishProgess(finishProgess);
                        recordFilePackageVos.add(recordFilePackageVo);
                    }
                }
                Map data = new HashMap<String,Object>();
                data.put("list",recordFilePackageVos);
                data.put("total",speakingPackages.getTotalElements());
                data.put("timestamp",timeStamp);
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",data);
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte(e.getMessage());
        }
        return defaultResult;
    }

    //公用的话术包
    @ResponseBody
    @RequestMapping("viewPublicSpeakingPackage")
    public DefaultResult viewPublicSpeakingPackage(String jsonStr){
        logger.info("queryPublicSpeakingFlowStep，jsonStr:"+jsonStr);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        Map params = JSON.parseObject(jsonStr,Map.class);
        try {
            if(params!=null && !params.isEmpty() && params.containsKey("page") && params.containsKey("pageSize")){
                //根据该package获取所有的话术
                Long timeStamp = System.currentTimeMillis();
                if(params.containsKey("timeStamp")){
                    timeStamp = Long.parseLong(params.get("timeStamp").toString());
                }
                Date createTime = Utils.long2Date(timeStamp);
                String createTimeEnd = Utils.date2DateTimeString(createTime);
                params.put("createTimeEnd",createTimeEnd);
                params.put("contentNoEmpty","");
                params.put("packageId","null");
                params.put("flowId","null");
                Page<SpeakingFlowStep> speakingFlowSteps = speakingFlowStepBiz.getSpeakingFlowStepByPage(params);
                List<RecordFileVo> recordFileVos = new ArrayList<RecordFileVo>();
                if(speakingFlowSteps.getContent()!=null && !speakingFlowSteps.getContent().isEmpty()){
                    for (SpeakingFlowStep speakingFlowStep:speakingFlowSteps){
                        RecordFileVo recordFileVo = new RecordFileVo();
                        recordFileVo.setId(speakingFlowStep.getId());
                        recordFileVo.setContent(speakingFlowStep.getContent());
                        recordFileVo.setName(speakingFlowStep.getStepName());
                        recordFileVo.setHadUploadFile(speakingFlowStep.getHadUploadFile());
                        recordFileVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                        recordFileVo.setRecordFileUrl(speakingFlowStep.getRecordFileUrl());
                        recordFileVos.add(recordFileVo);
                    }
                }
                Map data = new HashMap<String,Object>();
                data.put("list",recordFileVos);
                data.put("total",speakingFlowSteps.getTotalElements());
                data.put("timestamp",timeStamp);
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",data);
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("查询异常,"+e.getMessage());
        }
        return defaultResult;
    }


    ///查看话术包详情===话术包相应的话术
    @ResponseBody
    @RequestMapping("/viewSpeakingPackage")
    public DefaultResult viewSpeakingPackage(String jsonStr){
        Map params = JSON.parseObject(jsonStr,Map.class);
        logger.info("viewSpeakingPackage",params);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try {
            if(params!=null && !params.isEmpty() && params.containsKey("packageId") && params.containsKey("page") && params.containsKey("pageSize")){
                //根据该package获取所有的话术
                Long timeStamp = System.currentTimeMillis();
                if(params.containsKey("timeStamp")){
                    timeStamp = Long.parseLong(params.get("timeStamp").toString());
                }
                Date createTime = Utils.long2Date(timeStamp);
                String createTimeEnd = Utils.date2DateTimeString(createTime);
                params.put("createTimeEnd",createTimeEnd);
                params.put("contentNoEmpty","");
                Page<SpeakingFlowStep> speakingFlowSteps = speakingFlowStepBiz.getSpeakingFlowStepByPage(params);
                List<RecordFileVo> recordFileVos = new ArrayList<RecordFileVo>();
                if(speakingFlowSteps.getContent()!=null && !speakingFlowSteps.getContent().isEmpty()){
                    for (SpeakingFlowStep speakingFlowStep:speakingFlowSteps){
                        RecordFileVo recordFileVo = new RecordFileVo();
                        recordFileVo.setId(speakingFlowStep.getId());
                        recordFileVo.setContent(speakingFlowStep.getContent());
                        recordFileVo.setName(speakingFlowStep.getStepName());
                        recordFileVo.setHadUploadFile(speakingFlowStep.getHadUploadFile());
                        recordFileVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                        recordFileVo.setRecordFileUrl(speakingFlowStep.getRecordFileUrl());
                        recordFileVo.setPackageId(speakingFlowStep.getPackageId());
                        recordFileVo.setFlowId(speakingFlowStep.getFlowId());
                        recordFileVo.setType(speakingFlowStep.getType().getValue());
                        recordFileVos.add(recordFileVo);
                    }
                }
                Map data = new HashMap<String,Object>();
                data.put("list",recordFileVos);
                data.put("total",speakingFlowSteps.getTotalElements());
                data.put("timestamp",timeStamp);
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",data);
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return defaultResult;
    }

    //查看话术包流程
    @ResponseBody
    @RequestMapping("/viewSpeakingFlows")
    public DefaultResult viewSpeakingFlows(String jsonStr){
        Map params = JSON.parseObject(jsonStr,Map.class);
        logger.info("viewSpeakingPackage",params);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try {
            if(params!=null && !params.isEmpty() && params.containsKey("packageId") && params.containsKey("page") && params.containsKey("pageSize")){
                //根据该package获取所有的话术
                Long timeStamp = System.currentTimeMillis();
                if(params.containsKey("timeStamp")){
                    timeStamp = Long.parseLong(params.get("timeStamp").toString());
                }
                Date createTime = Utils.long2Date(timeStamp);
                String createTimeEnd = Utils.date2DateTimeString(createTime);
                params.put("createTimeEnd",createTimeEnd);
                params.put("contentNoEmpty","");
                Page<SpeakingFlow> speakingFlows = speakingFlowBiz.getSpeakingFlowByPage(params);
                List<RecordFilePackageVo> recordFilePackageVos = new ArrayList();
                for(SpeakingFlow speakingFlow:speakingFlows.getContent()){
                    if(speakingFlow.getFlowType() == null){
                        continue;
                    }
                    RecordFilePackageVo recordFilePackageVo = new RecordFilePackageVo();
                    recordFilePackageVo.setPageckName(speakingFlow.getFlowName());
                    recordFilePackageVo.setId(speakingFlow.getId());
                    recordFilePackageVo.setModTime(speakingFlow.getModTime()==null?speakingFlow.getCreateTime():null);
                    recordFilePackageVo.setModeTimeStr(Utils.date2DateString(speakingFlow.getModTime()));
                    //根据话术包获取完成量===>总的已经录音的话术
                    Map param = new HashMap();
                    param.put("packageId",speakingFlow.getPackageId());
                    param.put("contentNoEmpty","");
                    //跟进话术包获取总量===>总的需要录入的话术
                    List<SpeakingFlowStep> speakingFlowStepList = speakingFlowStepBiz.getSpeakingFlowStepByFlowId(speakingFlow.getId());
                    int sum = 0;
                    int finishedCount = 0;
                    if(speakingFlowStepList!=null && !speakingFlowStepList.isEmpty()){
//                        sum += speakingFlowStepList.size();
                        for(SpeakingFlowStep speakingFlowStep:speakingFlowStepList){
                            if(!Utils.isNullString(speakingFlowStep.getContent())){
                                sum++;
                                if(speakingFlowStep.getHadUploadFile() == true){
                                    finishedCount++;
                                }
                            }
                        }
                    }
                    recordFilePackageVo.setFinishedNum(finishedCount);
                    recordFilePackageVo.setTotalNum(sum);
                    recordFilePackageVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                    String finishProgess = "0";
                    if(recordFilePackageVo.getFinishedNum()>0 && recordFilePackageVo.getTotalNum()>0){
                        DecimalFormat decimalFormat = new DecimalFormat("0");
                        finishProgess = decimalFormat.format(Utils.getRate(recordFilePackageVo.getFinishedNum(),recordFilePackageVo.getTotalNum())*100);
                    }
                    recordFilePackageVo.setFinishProgess(finishProgess);
                    recordFilePackageVo.setFlowType(speakingFlow.getFlowType().getValue());
                    recordFilePackageVos.add(recordFilePackageVo);
                }
                Map data = new HashMap<String,Object>();
                data.put("list",recordFilePackageVos);
                data.put("total",speakingFlows.getTotalElements());
                data.put("timestamp",timeStamp);
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",data);
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("");
            e.printStackTrace();
        }
        return defaultResult;
    }





    //分页获取知识库的接口
    @ResponseBody
    @RequestMapping("/queryKnowledgePages")
    public DefaultResult queryKnowledgePages(String jsonStr){
        Map params = JSON.parseObject(jsonStr,Map.class);
        logger.info("queryKnowledgePages",params);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try{
            if(params!=null && !params.isEmpty() && params.containsKey("page") && params.containsKey("pageSize")){
                //根据该package获取所有的话术
                Long timeStamp = System.currentTimeMillis();
                if(params.containsKey("timeStamp")){
                    timeStamp = Long.parseLong(params.get("timeStamp").toString());
                }
                Date createTime = Utils.long2Date(timeStamp);
                String createTimeEnd = Utils.date2DateTimeString(createTime);
                params.put("createTimeEnd",createTimeEnd);
                Page<KnowledgeBase> knowledgeBasePage =  knowledgeBaseBiz.getKnowledgeBaseByPage(params);
                Map data = new HashMap<String, Object>();
                List<RecordFilePackageVo> recordFilePackageVos = new ArrayList();
                if(knowledgeBasePage.getContent()!=null && !knowledgeBasePage.getContent().isEmpty()){
                    for(KnowledgeBase knowledgeBase:knowledgeBasePage.getContent()){
                        RecordFilePackageVo recordFilePackageVo = new RecordFilePackageVo();
                        recordFilePackageVo.setPageckName(knowledgeBase.getTitle());
                        recordFilePackageVo.setId(knowledgeBase.getId());
                        recordFilePackageVo.setModTime(knowledgeBase.getModTime());
                        recordFilePackageVo.setModeTimeStr(Utils.date2DateString(knowledgeBase.getModTime()));
                        if(knowledgeBase.getOneToOneResult()!=null && !knowledgeBase.getOneToOneResult().isEmpty()){
                            int totalCount = knowledgeBase.getOneToOneResult().size();
                            recordFilePackageVo.setTotalNum(knowledgeBase.getOneToOneResult().size());
                            if(knowledgeBase.getResultRecordFile()!=null && !knowledgeBase.getResultRecordFile().isEmpty()){
                                int finshedCount = knowledgeBase.getOneToOneResult().size()-knowledgeBase.getResultRecordFile().size();
                                recordFilePackageVo.setFinishedNum(finshedCount>totalCount?totalCount:finshedCount);
                            }else{
                                recordFilePackageVo.setFinishedNum(knowledgeBase.getOneToOneResult().size());
                            }
                        }
                        recordFilePackageVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                        String finishProgess = "0";
                        if(recordFilePackageVo.getFinishedNum()>0 && recordFilePackageVo.getTotalNum()>0){
                            DecimalFormat decimalFormat = new DecimalFormat("0");
                            finishProgess = decimalFormat.format(Utils.getRate(recordFilePackageVo.getFinishedNum(),recordFilePackageVo.getTotalNum())*100);
                        }
                        recordFilePackageVo.setFinishProgess(finishProgess);
                        recordFilePackageVos.add(recordFilePackageVo);
                    }
                }
                data.put("list", recordFilePackageVos);
                data.put("total", knowledgeBasePage.getTotalElements());
                data.put("timestamp", timeStamp);
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("", data);
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("操作异常,"+e.getMessage());
        }
        return defaultResult;
    }

    ///查看话术包详情===话术包相应的话术
    @ResponseBody
    @RequestMapping("/viewKnowledgeAnswers")
    public DefaultResult viewKnowledgeAnswers(String id){
        logger.info("viewKnowledgeAnswers",id);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try {
            if(!Utils.isNullString(id)){
                KnowledgeBase knowledgeBase = knowledgeBaseBiz.selectById(id);
                if(knowledgeBase==null){
                    defaultResult = WebResultUtils.getFailCharDefaultResulte("没有找到对应的知识库数据");
                    return defaultResult;
                }
                List<RecordFileVo> recordFileVos = new ArrayList<RecordFileVo>();
                if(knowledgeBase.getKnowledgeBaseResultVos()!=null && !knowledgeBase.getKnowledgeBaseResultVos().isEmpty()){
                    for(int i=0;i<knowledgeBase.getKnowledgeBaseResultVos().size();i++){
                        RecordFileVo recordFileVo = new RecordFileVo();
                        recordFileVo.setId(knowledgeBase.getId());
                        recordFileVo.setContent(knowledgeBase.getKnowledgeBaseResultVos().get(i).getContent());
                        recordFileVo.setName(knowledgeBase.getTitle());
                        recordFileVo.setHadUploadFile(knowledgeBase.getHadUploadFile());
                        recordFileVo.setUploadRecordFileType(UploadRecordFileType.KNOWLEDGE.getValue());
                        recordFileVo.setIndex(knowledgeBase.getKnowledgeBaseResultVos().get(i).getId());
                        recordFileVo.setRecordFileUrl(knowledgeBase.getKnowledgeBaseResultVos().get(i).getRecordFileUrl()!=null?knowledgeBase.getKnowledgeBaseResultVos().get(i).getRecordFileUrl():"");
                        recordFileVos.add(recordFileVo);
                    }
                }
                Map data = new HashMap<String,Object>();
                data.put("list",recordFileVos);
                data.put("total",recordFileVos.size());
                data.put("timestamp",null);
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",data);
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return defaultResult;
    }

    //分页获取知识库 by packageId 的接口
    @ResponseBody
    @RequestMapping("/queryKnowledgePagesByPackageId")
    public DefaultResult queryKnowledgePagesByPackageId(String jsonStr){
        Map params = JSON.parseObject(jsonStr,Map.class);
        logger.info("queryKnowledgePages",params);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try{
            if(params!=null && !params.isEmpty() && params.containsKey("page") && params.containsKey("pageSize") && params.containsKey("packageId")){
                //根据该package获取所有的话术
                Long timeStamp = System.currentTimeMillis();
                if(params.containsKey("timeStamp")){
                    timeStamp = Long.parseLong(params.get("timeStamp").toString());
                }
                Date createTime = Utils.long2Date(timeStamp);
                String createTimeEnd = Utils.date2DateTimeString(createTime);
                params.put("createTimeEnd",createTimeEnd);
                Page<KnowledgeBase> knowledgeBasePage =  knowledgeBaseBiz.getKnowledgeBaseByPage(params);
                Map data = new HashMap<String, Object>();
                List<RecordFilePackageVo> recordFilePackageVos = new ArrayList();
                if(knowledgeBasePage.getContent()!=null && !knowledgeBasePage.getContent().isEmpty()){
                    for(KnowledgeBase knowledgeBase:knowledgeBasePage.getContent()){
                        RecordFilePackageVo recordFilePackageVo = new RecordFilePackageVo();
                        recordFilePackageVo.setPageckName(knowledgeBase.getTitle());
                        recordFilePackageVo.setId(knowledgeBase.getId());
                        recordFilePackageVo.setModTime(knowledgeBase.getModTime());
                        recordFilePackageVo.setModeTimeStr(Utils.date2DateString(knowledgeBase.getModTime()));
                        if(knowledgeBase.getOneToOneResult()!=null && !knowledgeBase.getOneToOneResult().isEmpty()){
                            int totalCount = knowledgeBase.getOneToOneResult().size();
                            recordFilePackageVo.setTotalNum(knowledgeBase.getOneToOneResult().size());
                            if(knowledgeBase.getResultRecordFile()!=null && !knowledgeBase.getResultRecordFile().isEmpty()){
                                int finshedCount = knowledgeBase.getOneToOneResult().size()-knowledgeBase.getOneToOneResult().size();
                                recordFilePackageVo.setFinishedNum(finshedCount>totalCount?totalCount:finshedCount);
                            }else{
                                recordFilePackageVo.setFinishedNum(knowledgeBase.getOneToOneResult().size());
                            }
                        }
                        recordFilePackageVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                        String finishProgess = "0";
                        if(recordFilePackageVo.getFinishedNum()>0 && recordFilePackageVo.getTotalNum()>0){
                            DecimalFormat decimalFormat = new DecimalFormat("0");
                            finishProgess = decimalFormat.format(Utils.getRate(recordFilePackageVo.getFinishedNum(),recordFilePackageVo.getTotalNum())*100);
                        }
                        recordFilePackageVo.setFinishProgess(finishProgess);
                        recordFilePackageVo.setHowAskQuestion(knowledgeBase.getHowAskQuestions());
                        recordFilePackageVos.add(recordFilePackageVo);
                    }
                }
                data.put("list", recordFilePackageVos);
                data.put("total", knowledgeBasePage.getTotalElements());
                data.put("timestamp", timeStamp);
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("", data);
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("操作异常,"+e.getMessage());
        }
        return defaultResult;
    }




    //登录接口
    @ResponseBody
    @RequestMapping("/login")
    public DefaultResult login(String jsonStr){
        Map params = JSON.parseObject(jsonStr,Map.class);
        logger.info("login",params);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try{
            if(params!=null && !params.isEmpty()){
                if(params.containsKey("userName") && params.containsKey("passWord")){
                    if("admin".equals(params.get("userName")) && "123456".equals(params.get("passWord"))){
                        defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",null);
                    }
                }else{
                    defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
                }
            }else{
                defaultResult = WebResultUtils.getFailCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("参数异常,"+e.getMessage());
        }
        return defaultResult;
    }



    /**
     * 上传录音 并 存储对应的 recordCodeNum 值
     * */
    @ResponseBody
    @RequestMapping("/uploadRecordFileAndSaveCodeNum")
    public DefaultResult uploadRecordFileAndSaveCodeNum(HttpServletRequest request,String uploadType,String id,String index){
        logger.info("uploadRecordFile",uploadType,id);
        if(!Utils.isNumber(index)){
            return WebResultUtils.getFailCharDefaultResulte("参数异常");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> list = multipartRequest.getFileNames();
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        UploadRecordFileType uploadRecordFileType = UploadRecordFileType.fromValue(uploadType);
        int fileNum = 0;
        LinkedList<String> fileUrlList = new LinkedList<String>();
        LinkedList<String> realFileNameList = new LinkedList<String>();
        try {
            while (list.hasNext()){
                fileNum++;
                String fileName  = list.next();
                if(fileName!=null){
                    MultipartFile voiceFile = multipartRequest.getFile(fileName);//语音文件
                    fileName = voiceFile.getOriginalFilename();
                    //*window下则在web容器的所在盘下，linux则在根目录下*//*
//                  路径
                    String line=File.separator;
                    String path=Thread.currentThread().getContextClassLoader().getResource("").toString();
                    //windows下
                   /* if("\\".equals(line)){
                        path = path.replace("/", "\\");  // 将/换成\\
                    }
                    //linux下
                    if("/".equals(line)){
                        path = path.replace("\\", "/");
                    }*/
                    File filePath = new File(PublicConfig.RECORDFILEPATH);
                    if (!filePath.exists()) {
                        filePath.createNewFile();
                    }

                    if (voiceFile!=null && !voiceFile.isEmpty()) {
                        String lastName = voiceFile.getOriginalFilename().substring(voiceFile.getOriginalFilename().lastIndexOf("."), voiceFile.getOriginalFilename().length()).toLowerCase();

                        if (lastName.indexOf("amr") == -1 && lastName.indexOf("mp3") == -1) {
                            defaultResult = WebResultUtils.getFailCharDefaultResulte("附件格式错误");
                        } else {
                            try {
                                //存在文件
                                if (voiceFile.getSize() > 0) {
                                    //上传音频文件
                                    String recordType = "OUT";
                                    String type = lastName.indexOf("amr")!=-1?"amr":(lastName.indexOf("mp3")!=-1?"mp3":"");
                                    String realFileName = fileName.substring(0,fileName.lastIndexOf("."));
                                    String fileSaveBasePath0 = filePath +line+ recordType+line+type+line+Utils.date2String(new Date(),"yyyyMMdd");
                                    String savePath = FileUtils.uploadFile(voiceFile,realFileName,fileSaveBasePath0,type);
                                    String serverName = request.getServerName();
                                    if("localhost".equals(serverName)){
                                        serverName = "172.16.6.92";
                                    }
                                    logger.info("保存成功，文件保存路径：{}",savePath);
                                    //访问录音的路径
                                    String urlPath = StringUtil.strConnect("api","/","recordFile",
                                            "/","getRecord","/",recordType,"/",type,"/",Utils.date2String(new Date(),"yyyyMMdd")+"/"+realFileName);
                                    String url = ("http://" + serverName + ":" +request.getServerPort()+request.getContextPath() +"/"+ urlPath);
                                    logger.info("branch up file url:{}",url);
                                    realFileNameList.add(realFileName);
                                    fileUrlList.add(url);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                defaultResult = WebResultUtils.getFailCharDefaultResulte("附件格式错误");
                            }
                        }
                    }
                }
            }
            //有文件情况下===进行更新操作
            if(fileNum>0 && fileUrlList.size() == fileNum){
                switch (uploadRecordFileType){
                    case SPEAKINGFLOWSTEP:
                        SpeakingFlowStep speakingFlowStep = speakingFlowStepBiz.getSpeakingFlowStepById(id);
                        if(speakingFlowStep==null){
                            defaultResult  = WebResultUtils.getFailCharDefaultResulte("没有找到对应的数据");
                            return defaultResult;
                        }
                        String fileUrl = Utils.getFirst(fileUrlList);
                        speakingFlowStep.setRecordFileUrl(fileUrl);
                        speakingFlowStep.setRecordCodeNum(Utils.getFirst(realFileNameList)+".wav");
                        speakingFlowStep.setHadUploadFile(true);
                        speakingFlowStep.setModTime(new Date());
                        speakingFlowStepBiz.update(speakingFlowStep);
                        SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(speakingFlowStep.getPackageId());
                        if(speakingPackage!=null){
                            speakingPackage.setModTime(new Date());
                            speakingPackageBiz.saveSpeakingPackage(speakingPackage);
                        }
                        break;
                    case KNOWLEDGE:
                        KnowledgeBase knowledgeBase = knowledgeBaseBiz.selectById(id);
                        if(knowledgeBase==null){
                            defaultResult  = WebResultUtils.getFailCharDefaultResulte("没有找到对应的数据");
                            return defaultResult;
                        }
                        //目前没有修改操作===只有录音上传操作，所以录了将新的add进去 ==== 之前录的则会被覆盖
                        LinkedHashMap<String, String>  resultRecordFile = knowledgeBase.getResultRecordFile();
                        for(int i=0;i<fileUrlList.size();i++){
                            if(resultRecordFile==null){
                                resultRecordFile = new LinkedHashMap<String, String>();
                            }
                            if(!resultRecordFile.isEmpty() &&  resultRecordFile.containsKey(index)){
                                resultRecordFile.remove(index);
                            }
                            resultRecordFile.put(index,fileUrlList.get(i));//将对应录音===存储起来
                        }

                        if(resultRecordFile.size() >= knowledgeBase.getOneToOneResult().size()){
                            knowledgeBase.setHadUploadFile(true);
                        }
//                      小程序一次只可以上传一条录音--》因此加上index标识上传哪条回答的录音 --》目前上传接口 仅处理单个录音'
                        knowledgeBase.setResultRecordFile(resultRecordFile);
                        knowledgeBase.setModTime(new Date());
                        knowledgeBaseBiz.update(knowledgeBase);
                        break;
                    default:
                        break;
                }
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("操作异常,"+e.getMessage());
        }
        return defaultResult;
    }


    //上传录音到话术的接口 --- 小程序一次只可以上传一条录音--》因此加上index标识上传哪条回答的录音 --》目前上传接口 仅处理单个录音
    @ResponseBody
    @RequestMapping("/uploadRecordFile")
    public DefaultResult uploadRecordFile(HttpServletRequest request,String uploadType,String id,String index){
        logger.info("uploadRecordFile",uploadType,id);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> list = multipartRequest.getFileNames();
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        UploadRecordFileType uploadRecordFileType = UploadRecordFileType.fromValue(uploadType);
        int fileNum = 0;
        LinkedList<String> fileUrlList = new LinkedList<String>();
        LinkedList<String> realFileNameList = new LinkedList<String>();
        try {
            while (list.hasNext()){
                fileNum++;
                String fileName  = list.next();
                if(fileName!=null){
                    MultipartFile voiceFile = multipartRequest.getFile(fileName);//语音文件
                    fileName = voiceFile.getOriginalFilename();
                    //*window下则在web容器的所在盘下，linux则在根目录下*//*
//                  路径
                    String line=File.separator;
                    String path=Thread.currentThread().getContextClassLoader().getResource("").toString();
                    //windows下
                   /* if("\\".equals(line)){
                        path = path.replace("/", "\\");  // 将/换成\\
                    }
                    //linux下
                    if("/".equals(line)){
                        path = path.replace("\\", "/");
                    }*/
                    File filePath = new File(PublicConfig.RECORDFILEPATH);
                    if (!filePath.exists()) {
                        filePath.createNewFile();
                    }

                    if (voiceFile!=null && !voiceFile.isEmpty()) {
                        String lastName = voiceFile.getOriginalFilename().substring(voiceFile.getOriginalFilename().lastIndexOf("."), voiceFile.getOriginalFilename().length()).toLowerCase();

                        if (lastName.indexOf("amr") == -1 && lastName.indexOf("mp3") == -1) {
                            defaultResult = WebResultUtils.getFailCharDefaultResulte("附件格式错误");
                        } else {
                            try {
                                //存在文件
                                if (voiceFile.getSize() > 0) {
                                    //上传音频文件
                                    String recordType = "OUT";
                                    String type = lastName.indexOf("amr")!=-1?"amr":(lastName.indexOf("mp3")!=-1?"mp3":"");
                                    String realFileName = fileName.substring(0,fileName.lastIndexOf("."));
                                    String fileSaveBasePath0 = filePath +line+ recordType+line+type+line+Utils.date2String(new Date(),"yyyyMMdd");
                                    String savePath = FileUtils.uploadFile(voiceFile,realFileName,fileSaveBasePath0,type);
                                    String serverName = request.getServerName();
                                    if("localhost".equals(serverName)){
                                        serverName = "172.16.6.92";
                                    }
                                    logger.info("保存成功，文件保存路径：{}",savePath);
                                    //访问录音的路径
                                    String urlPath = StringUtil.strConnect("api","/","recordFile",
                                            "/","getRecord","/",recordType,"/",type,"/",Utils.date2String(new Date(),"yyyyMMdd")+"/"+realFileName);
                                    String url = ("http://" + serverName + ":" +request.getServerPort()+request.getContextPath() +"/"+ urlPath);
                                    logger.info("branch up file url:{}",url);
                                    realFileNameList.add(realFileName);
                                    fileUrlList.add(url);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                defaultResult = WebResultUtils.getFailCharDefaultResulte("附件格式错误");
                            }
                        }
                    }
                }
            }
            //有文件情况下===进行更新操作
            if(fileNum>0 && fileUrlList.size() == fileNum){
                switch (uploadRecordFileType){
                    case SPEAKINGFLOWSTEP:
                        SpeakingFlowStep speakingFlowStep = speakingFlowStepBiz.getSpeakingFlowStepById(id);
                        if(speakingFlowStep==null){
                            defaultResult  = WebResultUtils.getFailCharDefaultResulte("没有找到对应的数据");
                            return defaultResult;
                        }
                        String fileUrl = Utils.getFirst(fileUrlList);
                        speakingFlowStep.setRecordFileUrl(fileUrl);
//                        speakingFlowStep.setRecordCodeNum(Utils.getFirst(realFileNameList)+".wav");
                        speakingFlowStep.setHadUploadFile(true);
                        speakingFlowStep.setModTime(new Date());
                        speakingFlowStepBiz.update(speakingFlowStep);
                        SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(speakingFlowStep.getPackageId());
                        if(speakingPackage!=null){
                            speakingPackage.setModTime(new Date());
                            speakingPackageBiz.saveSpeakingPackage(speakingPackage);
                        }
                        break;
                    case KNOWLEDGE:
                        KnowledgeBase knowledgeBase = knowledgeBaseBiz.selectById(id);
                        if(knowledgeBase==null){
                            defaultResult  = WebResultUtils.getFailCharDefaultResulte("没有找到对应的数据");
                            return defaultResult;
                        }
                        //目前没有修改操作===只有录音上传操作，所以录了将新的add进去 ==== 之前录的则会被覆盖
                        if(knowledgeBase.getKnowledgeBaseResultVos()!=null && !knowledgeBase.getKnowledgeBaseResultVos().isEmpty()){
                            Map<String,List<KnowledgeBaseResultVo>> idMaps = knowledgeBase.getKnowledgeBaseResultVos().stream().collect(Collectors.groupingBy(KnowledgeBaseResultVo::getId));
                            if(idMaps.containsKey(index)){
                                KnowledgeBaseResultVo knowledgeBaseResultVo = Utils.getFirst(idMaps.get(index));

                            }
                            int finishedCount = 0;
                            for (KnowledgeBaseResultVo knowledgeBaseResultVo:knowledgeBase.getKnowledgeBaseResultVos()){
                                if(!Utils.isNullString(knowledgeBaseResultVo.getRecordFileUrl())){
                                    finishedCount ++;
                                }
                                if(index.equals(knowledgeBaseResultVo.getId())){
                                    knowledgeBaseResultVo.setRecordFileUrl(fileUrlList.get(0));
                                }
                            }
                            if(finishedCount >= knowledgeBase.getKnowledgeBaseResultVos().size()){
                                knowledgeBase.setHadUploadFile(true);
                            }
                        }

//                      小程序一次只可以上传一条录音--》因此加上index标识上传哪条回答的录音 --》目前上传接口 仅处理单个录音'
//                        knowledgeBase.setResultRecordFile(resultRecordFile);
                        knowledgeBase.setModTime(new Date());
                        knowledgeBaseBiz.update(knowledgeBase);
                        break;
                    default:
                        break;
                }
                defaultResult = WebResultUtils.getSuccessCharDefaultResulte("",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("操作异常,"+e.getMessage());
        }
        return defaultResult;
    }

    /**
     * 语音读取文件,从hadoop mapFile
     *
     * @param request
     * @param response
     * @param key
     *
     */
    @RequestMapping(value = "getRecord/{recordType}/{type}/{yyyyMMdd}/{key}")//,headers = {"Content-Type=type/subtype"}
    public void getRecord(HttpServletRequest request, HttpServletResponse response,
                             @PathVariable String recordType,
                             @PathVariable String type,
                             @PathVariable String yyyyMMdd,
                             @PathVariable String key) {
        try {
            logger.debug("=================== key：{},type:{},date:{},mapFileName:{}",key,type,yyyyMMdd);

            if (StringUtil.isEmpty(key) ||
                    StringUtil.isEmpty(type) ||
                    StringUtil.isEmpty(yyyyMMdd)) {

                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("参数异常");

                return;
            }

            byte[] bytes = null;

            String localPath = StringUtil.strConnect(PublicConfig.RECORDFILEPATH,
                    File.separator,recordType,File.separator,type,File.separator,yyyyMMdd,File.separator,key,".",type);

            File file = new File(localPath);

            if(file.exists()){
                logger.debug("getFromLocal->localPath:{}", localPath);
                bytes = FileUtils.getBytes(file);
            }
            response.reset();
            response.setHeader("Accept-Ranges", "bytes");
            switch (type){
                case "mp3":
                    response.setContentType("audio/mp3");
                    break;
                case "wav":
                    response.setContentType("audio/wav");
                    break;
                case "ogg":
                    response.setContentType("application/ogg");
                    break;
            }
            logger.debug("sesionId file,byte size:{}",bytes.length);
            response.setContentLength(bytes.length);
            OutputStream outputStream = response.getOutputStream();//获取OutputStream输出流
            outputStream.write(bytes);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("读取文件失败!",e);
        }
    }


    /**
     * 语音读取文件,从hadoop mapFile
     *
     * @param request
     * @param response
     * @param key
     *
     */
    @RequestMapping(value = "getRecord/{recordType}/{type}/{type2}/{yyyyMMdd}/{key}")//,headers = {"Content-Type=type/subtype"}
    public void getRecord(HttpServletRequest request, HttpServletResponse response,
                          @PathVariable String recordType,
                          @PathVariable String type,
                          @PathVariable String yyyyMMdd,
                          @PathVariable String type2,
                          @PathVariable String key) {
        try {
            logger.debug("=================== key：{},type:{},date:{},mapFileName:{}",key,type,yyyyMMdd);

            if (StringUtil.isEmpty(key) ||
                    StringUtil.isEmpty(type) ||
                    StringUtil.isEmpty(yyyyMMdd)) {

                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("参数异常");

                return;
            }

            byte[] bytes = null;

            String localPath = StringUtil.strConnect(PublicConfig.RECORDFILEPATH,
                    File.separator,recordType,File.separator,type2,File.separator,type,File.separator,yyyyMMdd,File.separator,key,".",type);

            File file = new File(localPath);

            if(file.exists()){
                logger.debug("getFromLocal->localPath:{}", localPath);
                bytes = FileUtils.getBytes(file);
            }
            response.reset();
            response.setHeader("Accept-Ranges", "bytes");
            switch (type){
                case "mp3":
                    response.setContentType("audio/mp3");
                    break;
                case "wav":
                    response.setContentType("audio/wav");
                    break;
                case "ogg":
                    response.setContentType("application/ogg");
                    break;
            }
            logger.debug("sesionId file,byte size:{}",bytes.length);
            response.setContentLength(bytes.length);
            OutputStream outputStream = response.getOutputStream();//获取OutputStream输出流
            outputStream.write(bytes);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("读取文件失败!",e);
        }
    }

    /**
     * 传入客户方呼入数据返回分析和推荐话术结果
     * @param applet
     */
    @ResponseBody
    @RequestMapping("/analysisCustomerSpeaking")
    public String analysisCustomerSpeaking(String applet){
        logger.debug("=================== analysisCustomerSpeaking：applet{}",applet);
        String url = singleCallUrl+"/applet";
        String result = "";
        try {
            if(!Utils.isNullString(applet)){
                Map<String,String> params  = new HashMap<String,String>();
                params.put("applet",applet);
                result = HttpClientUtils.postMethod(url,params,null);
            }
        } catch (Exception e) {
            result = "获取接口异常："+ e.getMessage();
            e.printStackTrace();
        }
        return  result;
    }

    /**
     * 传入关于知识库的问题数据返回分析和答案
     * @param trainStr
     * */
    @Deprecated
    @ResponseBody
    @RequestMapping("/trainByKnowledgebase")
    public String trainByKnowledgebase(String trainStr){
        logger.debug("=================== trainByKnowledgebase：trainStr{}",trainStr);
        String url = singleCallUrl+"/knowledgebase";
        String result = "";
        try {
            if(!Utils.isNullString(trainStr)){
                Map<String,String> params  = new HashMap<String,String>();
                params.put("trainStr",trainStr);
                result = HttpClientUtils.postMethod(url,params,null);
            }
        } catch (Exception e) {
            result = "获取接口异常："+ e.getMessage();
            e.printStackTrace();
        }
        return  result;
    }


    /**
     *  语音解析
     * */
    @ResponseBody
    @RequestMapping("speechRecognition")
    public DefaultResult speechRecognition(HttpServletRequest request){
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try{
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator<String> list = multipartRequest.getFileNames();
            while (list.hasNext()){
                String fileName  = list.next();
                if(fileName!=null){
                    MultipartFile voiceFile = multipartRequest.getFile(fileName);//语音文件

                    //*window下则在web容器的所在盘下，linux则在根目录下*//*
//                  路径
                    String line=File.separator;
                    String path=Thread.currentThread().getContextClassLoader().getResource("").toString();
                    //windows下
                   /* if("\\".equals(line)){
                        path = path.replace("/", "\\");  // 将/换成\\
                    }
                    //linux下
                    if("/".equals(line)){
                        path = path.replace("\\", "/");
                    }*/
                    File filePath = new File(PublicConfig.RECORDFILEPATH);
                    if (!filePath.exists()) {
                        filePath.createNewFile();
                    }

                    if (voiceFile!=null && !voiceFile.isEmpty()) {
                        String lastName = voiceFile.getOriginalFilename().substring(voiceFile.getOriginalFilename().lastIndexOf("."), voiceFile.getOriginalFilename().length()).toLowerCase();

                        if (lastName.indexOf("amr") == -1 && lastName.indexOf("mp3") == -1) {
                            defaultResult = WebResultUtils.getFailCharDefaultResulte("附件格式错误");
                        } else {
                            try {
                                //存在文件
                                if (voiceFile.getSize() > 0) {
                                    //上传音频文件
                                    String recordType = "OUT";
                                    String type = lastName.indexOf("amr")!=-1?"amr":(lastName.indexOf("mp3")!=-1?"mp3":"");
                                    String realFileName = fileName.substring(0,fileName.lastIndexOf("."));
                                    String fileSaveBasePath0 = filePath +line+ recordType+line+type+line+Utils.date2String(new Date(),"yyyyMMdd");
                                    String pcmFileSaveBasePath0 = filePath +line+ recordType+line+"pcm"+line+Utils.date2String(new Date(),"yyyyMMdd");
                                    String savePath = FileUtils.uploadFile(voiceFile,realFileName,fileSaveBasePath0,type);
//                                    String savePcmPath = FileUtils.uploadFile(voiceFile,realFileName,fileSaveBasePath0,"pcm");
                                    FileUtils.checkAndCreateDir(pcmFileSaveBasePath0);
//                                    FileUtils.createFile(pcmFileSaveBasePath0,realFileName+".pcm");
                                    String savePcmPath = pcmFileSaveBasePath0+line+realFileName+".pcm";
                                    System.out.println(savePcmPath);
                                    String serverName = request.getServerName();
                                    if("localhost".equals(serverName)){
                                        serverName = "10.10.37.166";
                                    }
                                    logger.info("保存成功，文件保存路径：{}",savePath);
                                    //访问录音的路径
                                    String urlPath = StringUtil.strConnect("api","/","recordFile",
                                            "/","getRecord","/",recordType,"/",type,"/",Utils.date2String(new Date(),"yyyyMMdd")+"/"+realFileName);
                                    String url = ("http://" + serverName + ":" +request.getServerPort()+request.getContextPath() +"/"+ urlPath);
                                    logger.info("branch up file url:{},savePath",url,savePath);
                                    logger.info("trun file savePcmPath :{}",savePcmPath);
                                    String resultFile = FileUtils.changeVioceFileToPcm(profile,savePath,savePcmPath);
                                    logger.info("changeVioceToPcm :{}",resultFile);
                                    if(!Utils.isNullString(resultFile)){
                                        SpeechTranscriberMultiThread speechTranscriberMultiThread = new SpeechTranscriberMultiThread();
                                        String result = speechTranscriberMultiThread.doSpeechToText(SpeechFunctionInitBean.getSpeechTranscribeExecutor(),resultFile);
                                        Map<String,Object> data = new HashMap<String,Object>();
                                        data.put("resultStr", result);
                                        defaultResult = WebResultUtils.getSuccessCharDefaultResulte("", data);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                defaultResult = WebResultUtils.getFailCharDefaultResulte("操作失败 "+e.getMessage());
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("操作异常 "+e.getMessage());
        }
        return defaultResult;
    }

    //查看公共话术类型 树状
    @RequestMapping("/queryIndustryTypeTree")
    public DefaultResult queryIndustryTypeTree(String packageId){
        logger.debug("=================== queryIndustryTypePage：packageId{}",packageId);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try {
            //根据该package获取所有的话术
            Long timeStamp = System.currentTimeMillis();
            Map<String, Object> industryTree = industryTypeBiz.queryByTree(packageId,"treeNode","",false,true);
            Map data = new HashMap<String, Object>();
            if(industryTree!=null && !industryTree.isEmpty()){
                List<TreeNodeVo> treeNodeVos = (List<TreeNodeVo>)industryTree.get("data");
                List<Map<String,Object>> newDatas  = new ArrayList<>();
                try {
                    treeNodeVos.forEach(node->{
                        try {
                           if(!"0".equals(node.getValue())){
                               List<Map> childMaps = new ArrayList<>();
                               node.getChildren().forEach(childNode->{
                                   try {
                                       Map childNodeMap = Utils.objectToMap(childNode);
                                       Map param = new HashMap();
                                       param.put("packageId",((TreeNodeVo)childNode).getValue());
                                       long count1 = knowledgeBaseBiz.countKnowledgeBaseByField(param);
                                       childNodeMap.put("total",count1);
                                       childMaps.add(childNodeMap);
                                   } catch (Exception e) {
                                       e.printStackTrace();
                                   }
                               });
                               Map map = Utils.objectToMap(node);
                               map.put("children",childMaps);
                               Map paramMap = new HashMap();
                               paramMap.put("packageId",node.getValue());
                               long count = knowledgeBaseBiz.countKnowledgeBaseByField(paramMap);
                               map.put("total",count);
                               newDatas.add(map);
                           }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.put("list", newDatas);
                data.put("total", ((ArrayList)industryTree.get("data")).size());
            }else{
                data.put("list", null);
            }
            data.put("timestamp", timeStamp);
            defaultResult = WebResultUtils.getSuccessCharDefaultResulte("", data);
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("查询异常 "+e.getMessage());
        }
        return defaultResult;
    }

    //根据packageId 返回 指定 公共类型知识库
    /**
     * 如果已被覆盖需要进行标识操作
     * */
    @RequestMapping("/queryCommonsPageByPackageId")
    public DefaultResult queryCommonsPageByPackageId(String jsonStr){
        logger.debug("=================== queryCommonKnoledgesByPackageId：jsonStr{}",jsonStr);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try{
            Map<String,String> params = JSON.parseObject(jsonStr,Map.class);
            if(params!=null && !params.isEmpty() && params.containsKey("page") && params.containsKey("pageSize") && params.containsKey("packageId")){
                String packageId = params.get("packageId");
                SpeakingPackage speakingPackage =  speakingPackageBiz.getSpeakingPackageById(packageId);
                if(speakingPackage == null){
                    return  WebResultUtils.getFailCharDefaultResulte("没有找到对应的项目话术包信息~");
                }
                Long timeStamp = System.currentTimeMillis();
                if(params.containsKey("timeStamp")){
                    timeStamp = Long.parseLong(params.get("timeStamp").toString());
                }
                Date createTime = Utils.long2Date(timeStamp);
                String createTimeEnd = Utils.date2DateTimeString(createTime);
                params.put("createTimeEnd",createTimeEnd);

                List<String> industryTypeIds = speakingPackage.getAllIndustryTypeIds();
                if(industryTypeIds!=null && !industryTypeIds.isEmpty()){
                    Map<String,String> paramMap = new HashMap();
                    paramMap.put("packageId",packageId);
                    paramMap.put("overrideIdNoEmpty","");
                    //自定义知识库中覆盖了公共知识库的部分  根据packageId  、 引用的模板id不为空情况 返回的结果集
                    List<KnowledgeBase>  knowledgeBases = knowledgeBaseBiz.getKnowledgeBaseList(paramMap);
                    List<String> overrideIds = knowledgeBases.stream().map(it->it.getOverrideId()).collect(Collectors.toList());

                    Map<String,String> newParams = params;
                    Map<String,String> industryTypeMap = null;
                    //是否指定了 要查询的公共类型 id
                    if(params.containsKey("selIndustryTypeId") && !Utils.isNullString(params.get("selIndustryTypeId"))){
                        newParams.put("packageId", params.get("selIndustryTypeId"));
                        IndustryType industryType = industryTypeBiz.selectById(params.get("selIndustryTypeId"));
                        industryTypeMap = new HashMap<String,String>();
                        industryTypeMap.put(industryType.getId(),industryType.getName());
                    }else{//如果没有指定则 按 packageId 找到 该话术包所持有的 公共话术ids
                        Map<String,String> industryTypeParams = new HashMap<>();
                        industryTypeParams.put("ids", StringUtils.join(industryTypeIds,','));
                        List<IndustryType> industryTypes = industryTypeBiz.getIndustryTypesList(industryTypeParams);
                        industryTypeMap = industryTypes.stream().collect(toMap(IndustryType::getId,IndustryType::getName));
                        newParams.remove("packageId");
                        newParams.put("packageIds", StringUtils.join(industryTypeIds,','));
                    }
                    Page<KnowledgeBase>  commonknowledgeBases = knowledgeBaseBiz.getKnowledgeBaseByPage(newParams);
                    Map data = new HashMap<String, Object>();
                    List<RecordFilePackageVo> recordFilePackageVos = new ArrayList();
                    if(commonknowledgeBases.getContent()!=null && !commonknowledgeBases.getContent().isEmpty()){
                        for(KnowledgeBase knowledgeBase:commonknowledgeBases.getContent()){
                            RecordFilePackageVo recordFilePackageVo = new RecordFilePackageVo();
                            recordFilePackageVo.setPageckName(knowledgeBase.getTitle());
                            recordFilePackageVo.setId(knowledgeBase.getId());
                            recordFilePackageVo.setModTime(knowledgeBase.getModTime());
                            recordFilePackageVo.setModeTimeStr(Utils.date2DateString(knowledgeBase.getModTime()));
                            recordFilePackageVo.setRefPackageId(packageId);
                            if(knowledgeBase.getOneToOneResult()!=null && !knowledgeBase.getOneToOneResult().isEmpty()){
                                int totalCount = knowledgeBase.getOneToOneResult().size();
                                recordFilePackageVo.setTotalNum(knowledgeBase.getOneToOneResult().size());
                                if(knowledgeBase.getResultRecordFile()!=null && !knowledgeBase.getResultRecordFile().isEmpty()){
                                    int finshedCount = knowledgeBase.getOneToOneResult().size()-knowledgeBase.getOneToOneResult().size();
                                    recordFilePackageVo.setFinishedNum(finshedCount>totalCount?totalCount:finshedCount);
                                }else{
                                    recordFilePackageVo.setFinishedNum(0);
                                }
                            }
                            recordFilePackageVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                            String finishProgess = "0";
                            if(recordFilePackageVo.getFinishedNum()>0 && recordFilePackageVo.getTotalNum()>0){
                                DecimalFormat decimalFormat = new DecimalFormat("0");
                                finishProgess = decimalFormat.format(Utils.getRate(recordFilePackageVo.getFinishedNum(),recordFilePackageVo.getTotalNum())*100);
                            }
                            recordFilePackageVo.setFinishProgess(finishProgess);
                            if(overrideIds.contains(knowledgeBase.getId())){
                                recordFilePackageVo.setOverride(true);
                            }
                            recordFilePackageVo.setBelongIndustryTypeName(industryTypeMap.get(knowledgeBase.getId()));
                            recordFilePackageVo.setHowAskQuestion(knowledgeBase.getHowAskQuestions());
                            recordFilePackageVos.add(recordFilePackageVo);
                        }
                    }
                    data.put("list", recordFilePackageVos);
                    data.put("total", commonknowledgeBases.getTotalElements());
                    data.put("timestamp", timeStamp);
                    defaultResult = WebResultUtils.getSuccessCharDefaultResulte("", data);
                }
            }else{
                defaultResult = WebResultUtils.getExceptionCharDefaultResulte("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("查询操作异常,"+e.getMessage());
        }
        return defaultResult;
    }

    /**
     * 返回话术包下 持有的公共知识库类型
     * */
    @RequestMapping("/getCommonsTypeByPackageId")
    public DefaultResult getCommonsTypeByPackageId(String packageId){
        logger.debug("=================== getCommonsType：packageId{}",packageId);
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        try{
            Map data = new HashMap<String, Object>();
            SpeakingPackage speakingPackage =  speakingPackageBiz.getSpeakingPackageById(packageId);
            if(speakingPackage == null){
                return  WebResultUtils.getFailCharDefaultResulte("没有找到对应的项目话术包信息~");
            }
            List<String> industryTypeIds = speakingPackage.getAllIndustryTypeIds();
            Map<String,String> industryTypeParams = new HashMap<>();
            industryTypeParams.put("ids", StringUtils.join(industryTypeIds,','));
            List<IndustryType> industryTypes = industryTypeBiz.getIndustryTypesList(industryTypeParams);
            List<Map<String,String>> list = industryTypes.stream().map(it->{Map<String,String>  map = new HashMap<>();map.put("id",it.getId());map.put("name",it.getName());return map;}).collect(Collectors.toList());
            data.put("list", list);
            data.put("total", (list!=null && !list.isEmpty())?list.size():0);
            defaultResult = WebResultUtils.getSuccessCharDefaultResulte("", data);
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("查询操作异常,"+e.getMessage());
        }
        return defaultResult;
    }
}
